import Vue from 'vue'
import 'es6-promise/auto'
import Vuex from 'vuex'
import { getUserInfo } from '../utils'

Vue.use(Vuex)

const user = {
  state: {
    token: '',
    username: ''
  },
  mutations: {
    SET_USER (state, user) {
      if (user) {
        state.token = user.token
        state.username = user.username
        window.localStorage.setItem('userInfo', JSON.stringify(user))
      } else {
        state.token = ''
        state.username = ''
        window.localStorage.removeItem('userInfo')
      }
    }
  }
}

const article = {
  state: {
    editing: {
      title: '',
      content: ''
    }
  },
  mutations: {
    SET_ARTICLE (state, param) {
      state.editing = param
    }
  }
}

const store = new Vuex.Store({
  modules: {
    user,
    article
  },
  getters: {
    token: state => {
      if (!state.user.token) {
        let userInfo = getUserInfo()
        store.commit('SET_USER', userInfo)
      }
      return state.user.token
    },
    username: state => {
      const user = localStorage.getItem('user')
      const usename = user ? JSON.parse(user).username : ''
      return state.user.username || usename
    }
  }
})

export default store
